﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using Cinchoo.Core.ETL;
using Cinchoo.Core;
using Cinchoo.Core.Net.Sockets;
using Cinchoo.Core.Services;

namespace ChoWorkflowServer.Model
{
    public class ChoETLFeedbackService
    {
        private static readonly object _padLock = new object();

        public static readonly ChoQueuedExecutionService Queue = ChoQueuedExecutionService.GetService("FS_Q");
        public static readonly IChoDataModel DataModel = ChoDataModelFactory.New();

        private static ChoTcpClient _controller;
        public static ChoTcpClient Controller
        {
            set
            {
                _controller = value;
            }
        }

        public static void UpdateWorkflowStatus(ChoETLRuntime rt, object sender, PropertyChangedEventArgs e)
        {
            if (!(sender is ChoETLWorkflow)) return;

            lock (_padLock)
            {
                ChoETLWorkflow wf = sender as ChoETLWorkflow;
                ChoTcpClient controller = _controller;

                if (wf.BatchId != 0)
                {
                    Tuple<string, string> tuple = wf.JobName.FromJobName();

                    if (controller == null)
                    {
                        DataModel.AddOrUpdateTaskBatch(wf.BatchId, tuple.Item1, tuple.Item2, (int)wf.Status, wf.CmdParameters, null,
                            wf.LogMsg, wf.ProcessStart, wf.ProcessEnd, wf.Duration, null, wf.ExitCode,
                            wf.RetryCount, wf.Tag as string, Environment.MachineName);
                    }
                    else
                    {
                        ChoTaskFeedbackStatusCommand taskFeedbackStatusCommand = new ChoTaskFeedbackStatusCommand()
                        {
                            BatchId = wf.BatchId,
                            TaskName = tuple.Item1,
                            ScheduleName = tuple.Item2,
                            Status = (int)wf.Status,
                            CmdParameters = wf.CmdParameters,
                            LogMsg = wf.LogMsg,
                            ProcessStart = wf.ProcessStart,
                            ProcessEnd = wf.ProcessEnd,
                            Duration = wf.Duration,
                            NextRunTime = null,
                            ExitCode = wf.ExitCode,
                            RetryCount = wf.RetryCount,
                            ModifiedBy = wf.Tag as string
                        };
                        ChoCommandMessage commandMsg = new ChoCommandMessage();
                        commandMsg.Command = taskFeedbackStatusCommand;

                        controller.Send(commandMsg);
                    }
                }
                //else
                //    Console.WriteLine("0 BatchId");
            }
        }
    }
}
